import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:data_table_2/data_table_2.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:yuellyfactory/util/ColorUtil.dart';
import 'package:yuellyfactory/views/base/MaterialListEditVC.dart';
import 'package:yuellyfactory/views/base/MaterialListParmVC.dart';
import 'package:yuellyfactory/views/base/MaterialRuleVC.dart';
import 'package:yuellyfactory/views/dto/PriceMaterial.dart';
import 'package:yuellyfactory/views/dto/PriceParm.dart';
import 'package:yuellyfactory/views/dto/PricePart.dart';

import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshPart.dart';
import '../../util/BaseRequest.dart';
import '../../util/MathUtil.dart';
import '../../util/ToastUtil.dart';
import '../../util/ViewUtil.dart';
import '../dto/PriceRule.dart';
import 'MaterialParmVC.dart';

class MaterialListVC extends StatefulWidget {

  final PricePart pricePart;
  final VoidCallback callback;

  const MaterialListVC({super.key, required this.pricePart, required this.callback});

  @override
  State<MaterialListVC> createState() => _MaterialListVCState();
}

class _MaterialListVCState extends State<MaterialListVC> {

  String ruleStr="";
  StreamSubscription? streamSubscription;
  double tableHeight=0;
  List parmList=[];
  List allMaterials=[];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    streamSubscription = eventBus.on<EventRefreshPart>().listen((event) {
      getMaterialDetail();
    });

    getMaterialDetail();
  }

  @override
  void dispose() {
    if (streamSubscription != null) {
      streamSubscription!.cancel();
    }
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return ShadSheet(
      onClosing: (){
        widget.callback();
      },
      constraints: const BoxConstraints(minWidth: 800,maxWidth: 800),
      title:  Text("${widget.pricePart.name}   零件编辑"),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              Text('参数',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22)),),
              Expanded(child: Container()),
              ViewUtil.editIcon('编辑零件',(){
                showShadSheet(
                  barrierColor: Colors.transparent,
                  side: ShadSheetSide.right,
                  context: context,
                  builder: (context) =>  MaterialListParmVC(pricePart:widget.pricePart , callback: () {
                    //回调
                  },),
                );
              }),


            ],
          ),
          ViewUtil.lineView(),
          const SizedBox(height: 16),
          Row(
            children: [
              Text('单价计算公式',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22)),),
              Expanded(child: Container()),
              ViewUtil.editIcon('编辑公式',(){
                showShadSheet(
                  barrierColor: Colors.transparent,
                  side: ShadSheetSide.right,
                  context: context,
                  builder: (context) =>  MaterialRuleVC(pricePart:widget.pricePart , callback: () {
                    //回调
                  },),
                );
              }),

            ],
          ),
          Card(
              color: Colors.white,
              child:
              Container(
                padding: const EdgeInsets.only(left: 10,right: 10,top: 5,bottom: 5),
                alignment: Alignment.centerLeft,
                child: Text(getRuleString(ruleStr),style: const TextStyle(fontSize: 20),),
              )),
          ViewUtil.lineView(),
          const SizedBox(height: 16),
          Row(
            children: [
              Text('零件',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22)),),
              Expanded(child: Container()),
              ViewUtil.addIcon('新增零件',(){
                showShadSheet(
                  barrierColor: Colors.transparent,
                  side: ShadSheetSide.right,
                  context: context,
                  builder: (context) =>  MaterialListEditVC(pricePart:widget.pricePart ,priceMaterial: PriceMaterial(), callback: () {
                    //回调
                  },),
                );
              }),

              ViewUtil.importIcon("导入零件", (){

                selectFileToImport();
              }),



            ],
          ),

          Padding(
            padding: EdgeInsets.symmetric(horizontal: _outerPadding),
            child: Container(
              // 应用计算出的高度
              alignment: Alignment.centerLeft,
              height: tableHeight,
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey[200]!, width: _borderWidth),
                borderRadius: BorderRadius.circular(8),
              ),
              child: DataTable2(
                columnSpacing: 12,
                horizontalMargin: 12,
                minWidth: 3500,
                isHorizontalScrollBarVisible:true,
                headingRowHeight: _headerHeight - 2 * _borderWidth, // 减去边框占用高度
                dataRowHeight: _rowHeight - 2 * _borderWidth, // 减去边框占用高度
                // 表头
                columns: getTableHead(),

                // 表格内容（行高固定）
                rows: allMaterials.map((item) {
                  return DataRow(cells: getTableItem(item));
                }).toList(),
              ),
            ),
          ),
        ],
      ),

    );
  }


  List<DataColumn2> getTableHead(){
    List<DataColumn2> widgets=[];
    widgets.add(const DataColumn2(
      label: Text('  操作'),
      fixedWidth: 110,
    ),);

    for(var item in parmList){
      widgets.add(DataColumn2(label: Text(item.name),fixedWidth: 100,));
    }

    return widgets;
  }

  List<DataCell> getTableItem(PriceMaterial material){
    List<DataCell> widgets=[];
    widgets.add(DataCell(Row(children: [

      ViewUtil.editIcon('编辑零件',(){
        showShadSheet(
          barrierColor: Colors.transparent,
          side: ShadSheetSide.right,
          context: context,
          builder: (context) =>  MaterialListEditVC(pricePart:widget.pricePart ,priceMaterial: material, callback: () {
            //回调
          },),
        );

      }),
      ViewUtil.delIcon('删除零件',(){
        delMaterial(material);
      })
    ],)));

    for(var item in parmList){
      widgets.add(DataCell(Padding(
        padding: const EdgeInsets.symmetric(vertical: 12),
        child: Text(item.handle==1?

        getMaterialRuleString(item,material.data)

            :getParmValue(item.id,material.data)),
      )));
    }

    return widgets;
  }

  getMaterialRuleString(PriceParm parm,var data){
    if(data==null||data.length==0)return getRuleString(parm.rule);

    List datas=json.decode(data);
    String value="";
    for(var item in datas){
      if(item["id"]==parm.id){
        var handle=item["handle"];
        var v=item["rule"];
        if(handle!=null&&handle==1&&v!=null){
          if(v.contains("[")){
            value=v;
          }
        }
        break;
      }

    }



    debugPrint(parm.id+"==="+value);
    if(value.isNotEmpty){
      return getRuleString(value);
    }else{
      return getRuleString(parm.rule);
    }
  }

  getParmValue(String id,var data){
    if(data==null||data.length==0)return "";
    List datas=json.decode(data);
    var values={};
    for(var item in datas){
      values[item["id"]]=item["value"];
    }
    
    String value="";
    if(values.containsKey(id)){
      value=values[id].toString();
    }
    return value;
  }

  // 固定高度参数（可根据需求调整）
  final double _headerHeight = 56; // 表头高度（含内边距）
  final double _rowHeight = 88; // 每行高度（含内边距）
  final double _borderWidth = 1; // 边框宽度
  final double _outerPadding = 10; // 表格外间距


  // 计算表格总高度的核心方法
  double _calculateTableHeight(int length) {
    // 总高度 = 表头高度 + 数据行总高度 + 边框总高度
    // 边框高度：上下边框（2条）+ 行之间的分隔线（数据行数-1条）
    final int borderCount = 2 + (length - 1);
    final double totalBorderHeight = borderCount * _borderWidth;

    return _headerHeight + // 表头高度
        (_rowHeight * length) + // 所有数据行高度
        totalBorderHeight; // 边框总高度
  }


  getRuleString(var rule){

    var ruleStr="";
    if(rule.isNotEmpty){
      List<dynamic> list = json.decode(rule);

      for(var item in list){
        PriceRule rule=PriceRule.fromJson(item);
        if(rule.handle==0){
          ruleStr="$ruleStr${rule.value}";
        }else{
          ruleStr="$ruleStr${rule.name}";
        }
      }
    }
    if(ruleStr.isEmpty)ruleStr="未设置";

    return ruleStr;
  }



  void getMaterialDetail(){
    var parm={"id":widget.pricePart.id};

    BaseRequest.postHttp("price/materialdetail",parameters:parm , canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        dynamic datas=data["data"];
        PricePart pricePart= PricePart.fromJson(datas);
       // widget.pricePart.parmList=pricePart.parmList;
     //   widget.pricePart.materialRule=pricePart.materialRule;
        parmList=pricePart.parmList;
        pricePart!.parmList=pricePart.parmList;
        pricePart!.materialRule=pricePart.materialRule;
        ruleStr=pricePart.materialRule;
        allMaterials=pricePart.childMaterialList;
        tableHeight = _calculateTableHeight(allMaterials.length);
        setState(() {

        });

      }
    }, onError: (error){

    });
  }


  void delMaterial(PriceMaterial material){
    var parm={
      "id":material.id,
    };
    BaseRequest.postHttp("price/materialitemdel",parameters: parm, canTip: true, context: context, onSuccess: (data){

      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("删除成功");
        getMaterialDetail();
      }

    }, onError: (error){

    });
  }


  void selectFileToImport()async{
    FilePickerResult? result = await FilePicker.platform.pickFiles(
       );

    if (result != null) {
      File file = File(result.files.single.path!);
      debugPrint(file.path);
      requestToUpload(file.path);
    } else {
      // User canceled the picker
    }
  }

  void requestToUpload(String path){
    BaseRequest.uploadToImportMaterial(path: path, partId: widget.pricePart.id, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("操作成功");
        getMaterialDetail();
      }

    }, onError: (error){});
  }
}
